package com.zelin.homework.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpClientChat {
    public static void main(String[] args) {
        //定义扫描器用于输入
        Scanner scanner = new Scanner(System.in);

        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;

        try {
            while (true) {
                //创建客户端Socket对象,创建客户端
                socket = new Socket("localhost", 1014);
                //获得客户端输出流对象
                outputStream = socket.getOutputStream();

                //通过扫描器输入聊天内容
                System.out.print("客户端:");
                String input = scanner.next();

                //将输入内容转为输出流
                outputStream.write(input.getBytes());

                //获得客户端返回的内容
                inputStream = socket.getInputStream();
                //定义字节数组存放数据
                byte[] b = new byte[1024];
                //读入数据到数组
                inputStream.read(b);
                //数组里的数据转为字符串
                String s = new String(b);
                //打印服务端发送的数据
                System.out.println("服务端:" + s);

                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert inputStream != null;
                inputStream.close();
                outputStream.flush();
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
